import { _decorator, Component, EventKeyboard, Input, input, KeyCode, Layers, Node, SystemEvent, TiledLayer, TiledMap, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('playerController')
export class playerController extends Component {
    @property(Node)
    player: Node = null;

    @property(TiledMap)
    tiledMap: TiledMap = null;

    private loc: Vec3 = new Vec3();
    private notMoved: TiledLayer[] = null;
    private collidableLayer: TiledLayer[] = [];
    private availiablePos: Vec3 = new Vec3();

    protected onLoad(): void {
        input.on(Input.EventType.KEY_DOWN, this.move, this);
        this.notMoved = this.tiledMap.getLayers();

        for (let i = 0; i < this.notMoved.length; i++) {
            const layer = this.notMoved[i];
            const properties = layer.getProperties();
            if (properties && properties['Collidable']) {
                this.collidableLayer.push(layer);
            }
        }
    }

    private convertLocation() {
        let userLoc: Vec3 = this.player.position;
        let xTileSize = this.tiledMap.getTileSize().x;
        let yTileSize = this.tiledMap.getTileSize().y;
        let ySize = this.tiledMap.getMapSize().y * yTileSize;
        
        let userInTiled: Vec3 = new Vec3(userLoc.x, ySize - userLoc.y, 0);
        let xLocation = Math.floor(userInTiled.x / xTileSize);
        let yLocation = Math.floor(userInTiled.y / yTileSize);

        this.checkCollision(xLocation, yLocation);
    }

    private checkCollision(x: number, y: number) {
        let canMove: boolean = true;
        for (let i = 0; i < this.collidableLayer.length; i++) {
            if (this.collidableLayer[i].getTileGIDAt(x, y) != 0) {
                canMove = false;
                break;
            } else {
                canMove = true;
            }
        }
        if (canMove) {
            this.availiablePos.set(this.player.position);
        } else {
            this.player.setPosition(this.availiablePos);
        }

    }

    move(event: EventKeyboard){
        switch(event.keyCode){
            case KeyCode.KEY_W:
                this.loc.add(new Vec3(0, 10, 0));
                break;
            case KeyCode.KEY_S:
                this.loc.add(new Vec3(0, -10, 0));
                break;
            case KeyCode.KEY_A:
                this.loc.add(new Vec3(-10, 0, 0));
                break;
            case KeyCode.KEY_D:
                this.loc.add(new Vec3(10, 0, 0));
                break;
        }
        this.convertLocation();
        this.player.setPosition(this.loc);
    }

    start() {
        this.loc = this.node.position;
    }


    update(deltaTime: number) {
        
    }
}


